package picturetaker.persistence;

import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import picturetaker.domain.Camera;
import picturetaker.domain.CameraDomainMapper;
import picturetaker.domain.Picture;

public class ImageBroker {

	private static Connection con = null;

	protected ImageBroker() {
		con = Database.getConnection();
	}

	public List<Camera> getAllCameras() throws SQLException, MalformedURLException {
		Statement statement = con.createStatement();
		ResultSet result = statement.executeQuery("select camera_id, name, url from camera as result");
		return CameraDomainMapper.mapCameraListFromResultSet(result);
	}

	public void insertCamera(Camera camera) throws SQLException {
		Statement statement = con.createStatement();
		statement.execute("insert into camera (name, url) values ('" + camera.getCameraName() + "', '" + camera.getCameraUrl().toString() + "')");
	}

	public void insertPicture(Picture picture) throws SQLException {
		Statement statement = con.createStatement();
		statement.execute("insert into pic_data (pic) values ('" + picture.getPicData().getPath() + "')");

		ResultSet result = statement.executeQuery("select last_value from pic_data_pic_data_id_seq");

        if (result.next())
        {
            statement.execute("insert into picture (camera_id, mydate, name, pic_data_id, thumbnail, time) values ("
					+ picture.getCamera().getId() + ", '"
					+ picture.getDate() + "', '"
					+ picture.getName() + "',"
					+ result.getInt("last_value") + ", '"
					+ picture.getPath() + "', '"
					+ picture.getTime() + "')");
        }
	}
}
